package com.lizx.framework.web.smart.framework.core;

import com.google.gson.Gson;
import com.lizx.framework.web.smart.framework.core.helper.SmartBeanHelper;
import com.lizx.framework.web.smart.framework.core.helper.SmartConfigHelper;
import com.lizx.framework.web.smart.framework.core.helper.SmartControllerHelper;
import com.lizx.framework.web.smart.framework.core.utils.CodeUtil;
import com.lizx.framework.web.smart.framework.core.utils.SmartReflectionUtil;
import com.lizx.framework.web.smart.framework.core.utils.StreamUtil;
import com.lizx.framework.web.smart.framework.core.wrapper.DataWrapper;
import com.lizx.framework.web.smart.framework.core.wrapper.HandlerWrapper;
import com.lizx.framework.web.smart.framework.core.wrapper.ParamWrapper;
import com.lizx.framework.web.smart.framework.core.wrapper.ViewWrapper;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 核心控制器
 *
 * @Author: lizx
 * @Description:
 * @Date: Create in 2019/1/18 4:05 PM
 */
public class DispatherServlet extends HttpServlet {
    private static final long serialVersionUID = -6330975961422684857L;

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        HelperLoader.init();
        ServletContext servletContext = servletConfig.getServletContext();

        //注册处理jsp的servlet
        ServletRegistration jspServlet = servletContext.getServletRegistration("jsp");
        jspServlet.addMapping(SmartConfigHelper.getAppJspPath() + "*");

        //注册处理静态资源的servlet
        ServletRegistration defaultServlet = servletContext.getServletRegistration("default");
        defaultServlet.addMapping(SmartConfigHelper.getAppAssertPath() + "*");
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求方法与请求路径
        String requestMethod = req.getMethod().toLowerCase();
        String requestPath = req.getPathInfo();

        HandlerWrapper handler = SmartControllerHelper.getHandlerWrapper(requestMethod, requestPath);
        if (handler != null) {
            //获取controller对象及bean
            Class<?> controllerClass = handler.getControllerClass();
            Object controllerBean = SmartBeanHelper.getBean(controllerClass);

            //封装请求参数对象
            Map<String, Object> paramMap = new HashMap<>();
            Enumeration<String> paramNames = req.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String paramName = paramNames.nextElement();
                String paramValue = req.getParameter(paramName);
                paramMap.put(paramName, paramValue);
            }
            //解析url中的参数
            String body = CodeUtil.decodeURL(StreamUtil.getString(req.getInputStream()));
            if (StringUtils.isNotBlank(body)) {
                String[] params = StringUtils.split(body, "&");
                if (ArrayUtils.isNotEmpty(params)) {
                    for (String param : params) {
                        String[] array = StringUtils.split(param, "=");
                        if (ArrayUtils.isNotEmpty(array) && array.length == 2) {
                            String paramName = array[0];
                            String paramValue = array[1];
                            paramMap.put(paramName, paramValue);
                        }
                    }
                }
            }

            //反射调用request
            ParamWrapper param = new ParamWrapper(paramMap);
            Method actionMethod = handler.getActionMethod();
            Object result = SmartReflectionUtil.invokeMethod(controllerBean, actionMethod, param);
            System.out.println("11"+result);
            //封装返回值
            if (result instanceof ViewWrapper) {
                //jsp页面
                ViewWrapper view = (ViewWrapper) result;
                String path = view.getPath();
                if (StringUtils.isNotBlank(path)) {
                    if (path.startsWith("/")) {
                        resp.sendRedirect(req.getContextPath() + path);
                    } else {
                        Map<String, Object> model = view.getModel();
                        for (Map.Entry<String, Object> entry : model.entrySet()) {
                            req.setAttribute(entry.getKey(), entry.getValue());
                        }
                        req.getRequestDispatcher(SmartConfigHelper.getAppJspPath() + path).forward(req, resp);
                    }
                } else if (resp instanceof DataWrapper) {
                    //json数据
                    DataWrapper data = (DataWrapper) result;
                    Object model = data.getModel();
                    if (model != null) {
                        resp.setContentType("application/json");
                        resp.setCharacterEncoding("utf-8");
                        PrintWriter writer = resp.getWriter();
                        String json = new Gson().toJson(model);
                        writer.write(json);
                        writer.flush();
                        writer.close();
                    }
                }
            }
        }
    }
}
